/*
 * Copyright (c) 2021  Haowei Wen <yushijinhun@gmail.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "apriltag.hpp"
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/videoio.hpp>

int main(int argc, char *argv[]) {
  cv::VideoCapture cap;
  if (argc > 1) {
    cap.open(argv[1]);
  } else {
    cap.open(0);
  }
  if (!cap.isOpened()) {
    std::cerr << "Video is not opened!\n";
    return -1;
  }

  apriltag::Detector detector;
  cv::Mat image, gray;
  for (;;) {
    cap >> image;
    if (image.empty()) {
      break;
    }

    cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
    auto detections = detector.detect(gray);

    for (auto &det : detections) {

      // Draw frame
      cv::line(image, det.corners[0], det.corners[1], {0, 0xff, 0}, 2);
      cv::line(image, det.corners[0], det.corners[3], {0, 0, 0xff}, 2);
      cv::line(image, det.corners[1], det.corners[2], {0xff, 0, 0}, 2);
      cv::line(image, det.corners[2], det.corners[3], {0xff, 0, 0}, 2);

      // Draw text
      std::string text = std::to_string(det.id);
      int fontface = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;
      double fontscale = 1.0;
      int baseline;
      auto textsize = cv::getTextSize(text, fontface, fontscale, 2, &baseline);
      putText(image, text,
              {(int)det.center.x - textsize.width / 2,
               (int)det.center.y + textsize.height / 2},
              fontface, fontscale, {0xff, 0x99, 0}, 2);
    }

    cv::imshow("Tag Detections", image);
    cv::waitKey(30);
  }
}
